/**
 * 
 */
package com.jonosoft.photocast.viewer.web.client.photocast;

import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.HTTPRequest;
import com.google.gwt.user.client.ResponseTextHandler;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * TODO Add description PhotocastController
 * (com.jonosoft.photocast.viewer.web.client.PhotocastController)
 * 
 * @author jon
 * 
 */
public class PhotocastController {
	
	private static String RSS_TO_JSON_URL_PREFIX = "/cgi-bin/photocastAsJSON.pl?feed=";
	private static HTML scriptContainer = new HTML();
	private static int jsonIndex = 0;
	
	static {
		// can use this for user settings and stuff.
		DOM.appendChild(RootPanel.getBodyElement(), scriptContainer.getElement());
	}

	public static Photocast loadPhotocast(String photocastURL, PhotocastRecieveHandler handler) {
		Photocast photocast = new Photocast(photocastURL);
		String rssToJsonURL = RSS_TO_JSON_URL_PREFIX + photocastURL;

		HTTPRequest.asyncGet(rssToJsonURL, new HTTPPhotocastRecieveController(photocast, handler));

		return photocast;
	}

	private static class HTTPPhotocastRecieveController implements
	        ResponseTextHandler {
		private Photocast	photocast;
		private PhotocastRecieveHandler handler;

		public HTTPPhotocastRecieveController(Photocast photocast, PhotocastRecieveHandler handler) {
			this.photocast = photocast;
			this.handler = handler;
		}

		/**
		 * @see com.google.gwt.user.client.ResponseTextHandler#onCompletion(java.lang.String)
		 */
		public void onCompletion(String responseText) {
			//Debug.Out(responseText);
			photocast.setJSONRepresentation((JSONObject) JSONParser.parse(responseText));
			handler.onCompletion(photocast);
		}
	}

}
